package com.book.servlet;

import java.io.IOException;
import java.io.PrintWriter;
import java.util.ArrayList;
import java.util.Date;
import java.util.Iterator;
import java.util.List;
import java.util.Map;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import com.book.bean.CarGood;
import com.book.bean.OrderInfo;
import com.book.bean.OrderListInfo;
import com.book.bean.Users;
import com.book.biz.OrderInfoBiz;
import com.book.biz.OrderInfoListBiz;
import com.book.biz.impl.OrderInfoBizImpl;
import com.book.biz.impl.OrderInfoListBizImpl;
import com.book.dao.UserDao;
import com.book.dao.impl.UserDaoImpl;


public class AddOrderServlet extends HttpServlet {

	
	public void doGet(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		response.setContentType("text/html;charset=UTF-8");
		response.setCharacterEncoding("UTF-8");
		request.setCharacterEncoding("UTF-8");
		HttpSession session = request.getSession();
		PrintWriter out = response.getWriter();
		OrderInfo order=new OrderInfo();
		
		String uname = (String)request.getSession().getAttribute("uname");
		if(uname==null){
			request.getRequestDispatcher("/login_user.jsp").forward(request, response);
		}else{
			try {
				Users user = new UserDaoImpl().getUsers(uname);
				order.setUsers(user);
				order.setAddress(user.getAddress());
			} catch (Exception e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
			//创建订单明细的集合,从购物车中获取
			List<OrderListInfo> orIfList = new ArrayList<OrderListInfo>();
			Map<Integer, CarGood> carMap = (Map<Integer, CarGood>) session.getAttribute("map");
			Iterator<CarGood> itCar = carMap.values().iterator();
			OrderInfoBiz orBiz = new OrderInfoBizImpl();
			OrderInfoListBiz oiBiz = new OrderInfoListBizImpl();
			//遍历迭代器
			while(itCar.hasNext()){
				CarGood cg = itCar.next();
				OrderListInfo orIf = new OrderListInfo();
				orIf.setOrderInfo(order);
				orIf.setBook(cg.getBook());
				orIf.setPay(cg.getBook().getCost()*cg.getNum());
				orIf.setOlnum(cg.getNum());
				orIf.setOdate(new Date());
				orIfList.add(orIf);
			}
			order.setOrderInfoList(orIfList);
			boolean isOk = orBiz.addOrders(order);
			if(isOk){
				session.removeAttribute("map");
				request.setAttribute("order", order);
				response.sendRedirect("SelectOrderInfo.do?type=orderInfo");
				
			}else{
				request.getRequestDispatcher("/error.jsp").forward(request, response);
			}
		}
	}

	public void doPost(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {

		this.doGet(request, response);
		
	}

}
